<template>
    <div>
        <a-upload-dragger name="file" :multiple="true" :action="updateFile" @change="handleChange" :data="{}"
            :before-upload="beforeUpload" :fileList="fileList" list-type="picture-card" @preview="handlePreview">
            <p class="ant-upload-drag-icon">
                <a-icon type="inbox" />
            </p>
            <p class="ant-upload-text">
                点击上传
            </p>
            <p class="ant-upload-hint">
                支持单次或批量上传
            </p>
        </a-upload-dragger>
        <!-- {{ fileList }} -->
        <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
            <img alt="example" style="width: 100%" :src="previewImage" />
        </a-modal>
    </div>
</template>
<script>
export default {
    name: 'PPTUpImg',
    props: {
        dataIndex: {
            type: String,
        },
        onChangeForm: {
            type: Function,
            default: () => { }
        },
        formVal: {
            type: Object,
            default: () => { }
        }
    },
    data() {
        return {
            updateFile: '',
            fileList: [],
            previewVisible: false,
            previewImage: '',
        }
    },
    methods: {
        // 图片预览
        handleCancel() {
            this.previewVisible = false;
        },
        handleChange(e) {
            if (['image/jpeg', 'image/png'].includes(e.file.type)) {
                this.fileList = e.fileList;
                if (typeof (this.onChangeForm) == 'function') {
                    this.onChangeForm(this.dataIndex, this.fileList.map(val => val.response && val.response.data))
                }
            }
        },
        beforeUpload(file) {
            const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
            if (!isJpgOrPng) {
                this.$message.error('请上传图片');
            }
            return isJpgOrPng;
        },
        // 预览图片
        handlePreview(file) {
            this.previewImage = file.thumbUrl;
            this.previewVisible = true;
        }
    },
    mounted() {
        this.updateFile = this.$updateFileCommonQQCTN;
        if (Array.isArray(this.formVal.images)) {
            let imgArr = JSON.parse(JSON.stringify(this.formVal.images));
            this.fileList = imgArr.map((v, i) => {
                return {
                    uid: `${new Date()}${i}`,
                    status: 'done',
                    url: v,
                    thumbUrl: v,
                }
            });
        }
    },
}
</script>
<style lang="less" scoped></style>